package com.xingshang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xingshang.model.dto.GoodsDto;
import com.xingshang.model.po.Goods;
import com.xingshang.service.GoodsService;
import com.xingshang.mapper.GoodsMapper;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 87547
 * @description 针对表【wn_goods】的数据库操作Service实现
 * @createDate 2025-03-31 16:48:21
 */
@Service
@RequiredArgsConstructor
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods>
        implements GoodsService {

    private final GoodsMapper goodsMapper;
    private final RedisService redisService;

    private final MinioClient minioClient;

    @Value("${minio.bucket.files}")
    private String bucketName;

    @Override
    public List<Goods> selectNewAll() {

        return lambdaQuery().eq(Goods::getNewest, "Y").list();
    }

    @Override
    public List<Goods> selectHotAll() {
        return lambdaQuery().eq(Goods::getHottest, "Y").list();
    }

    @Override
    public IPage<Goods> findByPage(int page, int pageSize) {
        IPage<?> cachedData = redisService.getGoodsPage(page);
        if (cachedData != null) {
            System.out.println("使用缓存：第" + page + "页数据");
            System.out.println(cachedData);
            return (IPage<Goods>) cachedData;
        }
        IPage<Goods> goodsIPage = new Page<>(page, pageSize);
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("newest", "Y");
        IPage<Goods> goodsIPage1 = goodsMapper.selectPage(goodsIPage, queryWrapper);

        // 将数据存入缓存
        redisService.cacheGoodsPage(page, goodsIPage1);
        return goodsIPage1;
    }

    @Override
    public boolean insertGood(GoodsDto goodsDto) {

        return false;
    }

    /**
     * 生成唯一文件名
     *
     * @param originalFilename 原始文件名
     * @return 唯一文件名
     */
    private String generateFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        return uuid + extension;
    }

    @Override
    public String addMediaFilesToMinIO(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String fileName = generateFileName(originalFilename);
// 执行上传
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .contentType(file.getContentType())
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build()
        );
// 返回文件URL
        return getFileUrl(fileName);
    }

    /**
     * 获取文件的URL
     *
     * @param fileName 文件名
     * @return 文件URL
     * @throws Exception MinIO异常
     */
    public String getFileUrl(String fileName) throws Exception {
// 生成临时访问URL
        String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .method(Method.GET)
                        .expiry(7, TimeUnit.DAYS)
                        .build()
        );
        return url;
    }


}




